package com.qf.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/8/31 10:30
 * @Pacakge: com.qf.utils
 * @ClassName: ConnectionUtils
 * @Author: fan
 */
public class ConnectionUtils {
    //线程绑定
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //connection来源于dataSource
    private DataSource dataSource;
    //使用set方法进行注入
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public Connection getConnection(){
        try {
            Connection connection = threadLocal.get();
            if (connection == null){//没有连接对象
                //需要从数据库中获取一个连接对象
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将当前线程和连接对象进行解绑
     */
    public void removeConnection() {
        threadLocal.remove();
    }
}
